<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item>
        首页
      </el-breadcrumb-item>
      <el-breadcrumb-item><a href="/">商品管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片试图 -->
    <el-card>
      <!-- \警告区域 -->
      <el-alert
        title="注意： 只允许为第三季分类设置参数"
        type="warning"
        show-icon
        :closable="false"
      />
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类:</span>
          <!-- 选择级联框 -->
          <el-cascader
            v-model="selectedCate"
            :options="catelist"
            :props="casProp"
            @change="handleChange"
          />
        </el-col>
      </el-row>
      <!-- tab页签 -->
      <el-tabs
        v-model="activeName"
        @tab-click="handleClick"
      >
        <!-- 添加动态参数 -->
        <el-tab-pane
          label="动态参数"
          name="many"
        >
          <el-button
            size="mini"
            :disabled="isBtnDisabled"
            @click="addParamsDialogVisible = true"
          >
            添加参数
          </el-button>
          <!-- 动态参数表格 -->
          <el-table
            :data="manyTableData"
            border
            stripe
          >
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="handleClose(i,scope.row)"
                >
                  {{ item }}
                </el-tag>
                <!-- 输入文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                />
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >
                  + New Tag
                </el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" />
            <el-table-column
              label="参数名称"
              prop="attr_name"
            />
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                >
                  编辑
                </el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  @click="removePara(scope.row.attr_id)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态属性 -->
        <el-tab-pane
          label="静态属性"
          name="only"
        >
          <el-button
            size="mini"
            :disabled="isBtnDisabled"
            @click="addParamsDialogVisible = true"
          >
            添加参数
          </el-button>
          <!-- 静态参数表格 -->
          <el-table
            :data="onlyTableData"
            border
            stripe
          >
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="handleClose(i,scope.row)"
                >
                  {{ item }}
                </el-tag>
                <!-- 输入文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                />
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >
                  + New Tag
                </el-button>
              </template>
            </el-table-column>
            <el-table-column
              type="index"
              label="#"
            />
            <el-table-column
              label="参数名称"
              prop="attr_name"
            />
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                >
                  编辑
                </el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  @click="removePara(scope.row.attr_id)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加参数对话框 -->
    <el-dialog
      :title="titleText"
      :visible.sync="addParamsDialogVisible"
      width="50%"
      @close="addDialogClose"
    >
      <!-- 内容区域 -->
      <span>
        <el-form
          :model="addForm"
          :rules="addFormRules"
          ref="addFormRef"
          label-width="100px"
        >
          <el-form-item
            :label="titleText"
            prop="attr_name"
          >
            <el-input v-model="addForm.attr_name" />
          </el-form-item>
        </el-form>
      </span>
      <!-- 脚部 -->
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dialogVaddParamsDialogVisibleisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="addParams"
        >确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改参数对对话框 -->
    <el-dialog
      :title="'修改'+titleText"
      :visible.sync="editParamsDialogVisible"
      width="50%"
      @close="editDialogClose"
    >
      <!-- 内容区域 -->
      <span>
        <el-form
          :model="editForm"
          :rules="editFormRules"
          ref="editFormRef"
          label-width="100px"
        >
          <el-form-item
            :label="titleText"
            prop="attr_name"
          >
            <el-input v-model="editForm.attr_name" />
          </el-form-item>
        </el-form>
      </span>
      <!-- 脚部 -->
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="editParamsDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="editParams"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      editFormRules: {
        attr_name: [{ required: true, message: '请输入活动名称', trigger: 'blur' }]
      },
      // 编辑表单数据对象
      editForm: {

      },
      // 编辑参数对话框显示
      editParamsDialogVisible: false,
      addFormRules: {
        attr_name: [{ required: true, message: '请输入活动名称', trigger: 'blur' }]
      },
      // 添加参数对话框
      addParamsDialogVisible: false,
      // 被激活的页签的名称
      activeName: 'many',
      // 商品分类列表
      catelist: [],
      // 级联选择框配置属性
      casProp: { expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 级联选择框选定的级
      selectedCate: [],
      // 动态参数数据
      manyTableData: [],
      // 静态参数数据
      onlyTableData: [],
      // 添加参数表单数据对象
      addForm: {
        attr_name: ''
      }
    }
  },
  created () {
    this.getCate()
  },
  methods: {
    // 删除参数属性
    handleClose (i, row) {
      row.attr_vals.splice(i, 1)
      this.saveAttrVals()
    },
    // 点击按钮 显示文本框
    showInput (row) {
      row.inputVisible = true
      //  $nextTick 方法 就是当页面上元素被重新渲染之后 执行回调函数
      // 因为input是后来渲染出来的
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 文本框失去焦点或摁下entaer
    async handleInputConfirm (row) {
      console.log(row.attr_vals)
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      // 发起请求
      this.saveAttrVals(row)
    },
    async saveAttrVals (row) {
      // 发起请求
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) {
        return this.$message.error('修改参数失败')
      }
      this.$message.success('修改啊成功')
    },
    // 根据id删除参数
    async removePara (id) {
      const confirmResult = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消了删除')
      }
      const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      this.$message.success('删除成功')
      this.getParamsData()
    },
    // 点击按钮修改参数信息
    editParams () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) {
          return
        }
        const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`, {
          attr_name: this.editForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 200) {
          return this.$message.error('修改失败')
        }
        this.$message.success('修改成功')
        this.editParamsDialogVisible = false
        this.getParamsData()
      })
    },
    // 监听编辑对话框关闭
    editDialogClose () {
      this.$refs.editFormRef.resetFields()
    },
    // 点击按钮 展示对话框
    async showEditDialog (attrId) {
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/${attrId}`)
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数失败')
      }
      this.editForm = res.data
      this.editParamsDialogVisible = true
    },
    // tab页签点击事件
    handleClick () {
      this.getParamsData()
      console.log(this.activeName)
    },
    // 级联选择框选定的改变
    handleChange () {
      this.getParamsData()
    },
    // 获取参数列表数据
    async getParamsData () {
      // 证明选中的不是3级分类
      if (this.selectedCate.length !== 3) {
        this.selectedCate = []
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
      // 根据所选分类id 和当前面板 获取对应参数
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
        params: { sel: this.activeName }
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取列表失败')
      }
      // console.log(res.data)
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals.split(' ')
        if (item.attr_vals[0] === '') {
          item.attr_vals.pop()
        }
        item.inputVisible = false
        item.inputValue = ''
      })
      console.log(res.data)
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
      console.log(this.manyTableData)
    },
    async getCate () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.console.error(('获取商品列表失败'))
      }
      this.catelist = res.data
    },
    // 监听添加参数对话框关闭
    addDialogClose () {
      this.$refs.addFormRef.resetFields()
    },
    addParams () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return
        }
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) {
          return this.$message.error('添加参数失败')
        }
        this.getParamsData()
        this.addParamsDialogVisible = false
        this.$message.success('添加成功')
      })
    }
  },
  computed: {
    // 对话框标题
    titleText () {
      if (this.activeName === 'many') {
        return '添加动态参数'
      } else {
        return '添加静态属性'
      }
    },
    // 如果需要被禁用 返回true
    isBtnDisabled () {
      if (this.selectedCate.length !== 3) {
        return true
      }
      return false
    },
    // 当前选中的三级分类id
    cateId () {
      if (this.selectedCate.length === 3) {
        return this.selectedCate[2]
      }
      return null
    }
  }
}
</script>

<style scoped lang="less">
.cat_opt {
  margin: 15px 0
}
.input-new-tag {
  width: 120px
}
</style>
